import React, { useState, useRef, useEffect, useContext } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Modal,
  Image,
  TouchableWithoutFeedback,
  ScrollView,
  Alert,
  Dimensions,
  ActivityIndicator,
} from "react-native";
import MyQuesContext from "../../../context/questionnaire/MyQuesContext";
import LoadingBar from "../../../components/InterView/LoadingBar";

import * as ImagePicker from "expo-image-picker";
import ImageViewer from "react-native-image-zoom-viewer";
import VideoPlayer from "expo-video-player";
import { Audio } from "expo-av";
import * as DocumentPicker from "expo-document-picker";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import { ResizeMode } from "expo-av";
import { Feather } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { Foundation } from "@expo/vector-icons";
import AudioListItem from "../../../components/InterView/AudioListItem";
import { play, pause, resume, playNext } from "../../../utils/audioController";
import { fileWeb } from "../../../api/query";

const { width: DEVICE_WIDTH, height: DEVICE_HEIGHT } = Dimensions.get("window");

const Loading = ({ text }) => {
  return (
    <View style={styles.alterView}>
      <ActivityIndicator animating={true} size={"large"} color="#ddd" />
      <Text style={{ color: "#ccc", marginTop: 10 }}>{text}</Text>
    </View>
  );
};

const AddData = ({ navigation, route }) => {
  const { myQuesIndex } = route.params;
  const { fileDataLoading, MyQuesData, editFileData } =
    useContext(MyQuesContext);
  // console.log(MyQuesData[myQuesIndex].filedata);

  //加载可见性
  const [isConfirm, setIsConfirm] = useState(false);
  //拍照/打开相册可见性
  const [isVisible, setIsVisible] = useState(false);
  //摄像/打开相册可见性
  const [isVideoVisible, setIsVideoVisible] = useState(false);

  const [imageList, setImageList] = useState([]);
  //原始需保留的入户图片
  const [originImage, setOriginImage] = useState(
    MyQuesData[myQuesIndex].filedata.image
  );
  //原始需删除的入户图片
  const [deleteOriginImage, setDeleteOriginImage] = useState([]);
  //放大图片
  const [magnifypVisible, setMagnifypVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [imagesUrl, setimagesUrl] = useState([]);
  // 音频
  const [audioList, setAudioList] = useState([]);
  //原始需保留的入户音频
  const [originAudio, setOriginAudio] = useState(
    MyQuesData[myQuesIndex].filedata.soundfile
  );
  //原始需删除的入户音频
  const [deleteOriginAudio, setDeleteOriginAudio] = useState([]);
  const [currentAudio, setCurrentAudio] = useState({});
  const [currentAudioIndex, setCurrentAudioIndex] = useState(null);
  const [soundObj, setSoundObj] = useState(null);
  const [playbackObj, setPlaybackObj] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);
  //视频
  const refVideo = useRef(null);
  const [videoList, setvideoList] = useState([]);
  //原始需保留的入户视频
  const [originVideo, setOriginVideo] = useState(
    MyQuesData[myQuesIndex].filedata.video
  );
  //原始需删除的入户视频
  const [deleteOriginVideo, setDeleteOriginVideo] = useState([]);
  const [inFullscreen, setInFullsreen] = useState(false);
  //保存图片时需要MediaLibrary的权限
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();

  useEffect(() => {
    let isMounted = true;
    if (isMounted) {
      getPermission();
    }
    return () => {
      isMounted = false;
    };
  }, []);

  const permissionAllert = () => {
    Alert.alert("权限请求", "本App需要读取系统媒体库的权限", [
      {
        text: "允许",
        onPress: () => getPermission(),
      },
      {
        text: "不允许",
        onPress: () => alert("未授权访问媒体库的权限，请在设置中进行修改"),
      },
    ]);
  };

  const getPermission = async () => {
    const permission = await MediaLibrary.getPermissionsAsync();
    if (permission.granted) {
      setHasMediaLibraryPermission(true);
    }
    if (!permission.granted && permission.canAskAgain) {
      const { status, canAskAgain } =
        await MediaLibrary.requestPermissionsAsync();
      if (status === "granted") {
        setHasMediaLibraryPermission(true);
      }
      if (status === "denied" && canAskAgain) {
        permissionAllert();
      }
      if (status === "denied" && !canAskAgain) {
        alert("未授权访问媒体库的权限，请在设置中进行修改");
      }
    }
    if (!permission.canAskAgain && !permission.granted) {
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      // aspect: [1, 1],
      quality: 1,
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  const openCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setImageList([...imageList, result.uri]);
      setIsVisible(false);
    }
  };

  //  Unlike saveImageToPhone(), This method doesn't return created asset. On iOS 11+, it's possible to use this method without asking for CAMERA_ROLL permission.
  const saveImage = async (url) => {
    setIsConfirm(true);
    if (url.substring(0, 7) != "file://") {
      const localpicture = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "image.jpg"
      );
      if (localpicture.status != 200) {
        alert("下载失败！");
      } else {
        url = localpicture.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const deleteImage = (url) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let images = imageList.filter((item) => item !== url);
          setImageList(images);
        },
      },
    ]);
  };

  const deleteOriImage = (image) => {
    Alert.alert("提示", "要删除这张照片吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let images = originImage.filter((item) => item != image);
          setOriginImage(images);
          setDeleteOriginImage([...deleteOriginImage, image]);
        },
      },
    ]);
  };

  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  const openVideoCamera = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
    if (permissionResult.granted === false) {
      alert("您拒绝该应用使用您的相机");
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: true,
      quality: 1,
      // aspect: [4, 3],
    });
    if (!result.cancelled) {
      setvideoList([...videoList, result.uri]);
      setIsVideoVisible(false);
    }
  };

  const saveVideo = async (url) => {
    setIsConfirm(true);
    if (url.substring(0, 7) != "file://") {
      const localvideo = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + "video.mp4"
      );
      // console.log(localvideo);
      if (localvideo.status != 200) {
        setIsConfirm(false);
        alert("下载失败！");
      } else {
        url = localvideo.uri;
      }
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveVideoAlert = (url) => {
    Alert.alert("提示", "要保存这个视频吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveVideo(url);
        },
      },
    ]);
  };

  const deleteVideo = (url) => {
    Alert.alert("提示", "要删除这个视频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let videos = videoList.filter((item) => item !== url);
          setvideoList(videos);
        },
      },
    ]);
  };

  const deleteOriVideo = (video) => {
    Alert.alert("提示", "要删除这张视频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let videos = originVideo.filter((item) => item != video);
          setOriginVideo(videos);
          setDeleteOriginVideo([...deleteOriginVideo, video]);
        },
      },
    ]);
  };

  const pickAudio = async () => {
    let result = await DocumentPicker.getDocumentAsync({});
    if (result.type != "cancel") {
      if (result.mimeType.substring(0, 5) != "audio") {
        alert("请选择音频文件");
      } else {
        setAudioList([...audioList, { uri: result.uri, name: result.name }]);
      }
    }
  };

  const deleteAudio = (audio) => {
    Alert.alert("提示", "要删除这个音频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let audios = audioList.filter((item) => item !== audio);
          setAudioList(audios);
        },
      },
    ]);
  };

  const saveAudio = async (type, aduio) => {
    setIsConfirm(true);
    let url;
    if (type == 0) {
      url = fileWeb + "/" + aduio.filePath;
      const localvideo = await FileSystem.downloadAsync(
        url,
        FileSystem.documentDirectory + url.split("/").pop()
      );
      if (localvideo.status != 200) {
        setIsConfirm(false);
        alert("下载失败！");
      } else {
        url = localvideo.uri;
      }
    } else {
      url = aduio.uri;
    }
    if (hasMediaLibraryPermission) {
      try {
        MediaLibrary.saveToLibraryAsync(url).then(() => {
          setIsConfirm(false);
          alert("已保存到系统相册");
        });
      } catch (error) {
        setIsConfirm(false);
        alert("保存时出错了！");
      }
    } else {
      setIsConfirm(false);
      alert("未授权访问媒体库的权限，请在设置中进行修改");
    }
  };

  const saveAudioAlert = (type, audio) => {
    Alert.alert("提示", "要保存这个录音吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          saveAudio(type, audio);
        },
      },
    ]);
  };

  const deleteOriAudio = (audio) => {
    Alert.alert("提示", "要删除这个音频吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          let audios = originAudio.filter((item) => item != audio);
          setOriginAudio(audios);
          setDeleteOriginAudio([...deleteOriginAudio, audio]);
        },
      },
    ]);
  };

  //处理录音点击事件
  const handleAudioPress = async (audio) => {
    let index;
    let tag;
    if (originAudio.indexOf(audio) != -1) {
      index = originAudio.indexOf(audio);
      tag = 1;
    } else {
      index = audioList.indexOf(audio) + originAudio.length;
      tag = 2;
    }
    // playing audio for the first time.
    if (soundObj === null) {
      const playbackObj = new Audio.Sound();
      let status;
      if (tag == 1) {
        status = await play(playbackObj, fileWeb + "/" + audio.filePath);
      } else {
        status = await play(playbackObj, audio.uri);
      }
      setCurrentAudio(audio);
      setCurrentAudioIndex(index);
      setIsPlaying(true);
      setPlaybackObj(playbackObj);
      setSoundObj(status);

      playbackObj.setOnPlaybackStatusUpdate((playbackStatus) => {
        if (playbackStatus.didJustFinish) {
          setCurrentAudio({});
          setCurrentAudioIndex(null);
          setIsPlaying(false);
          setPlaybackObj(null);
          setSoundObj(null);
        }
      });
    } else {
      // pause audio
      if (
        soundObj.isLoaded &&
        soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await pause(playbackObj);
        setSoundObj(status);
        setIsPlaying(false);
      }
      // resume audio
      if (
        soundObj.isLoaded &&
        !soundObj.isPlaying &&
        index === currentAudioIndex
      ) {
        const status = await resume(playbackObj);
        setSoundObj(status);
        setIsPlaying(true);
      }
      // select another audio
      if (soundObj.isLoaded && index !== currentAudioIndex) {
        let status;
        if (tag == 1) {
          status = await playNext(playbackObj, fileWeb + "/" + audio.filePath);
        } else {
          status = await playNext(playbackObj, audio.uri);
        }
        setCurrentAudio(audio);
        setSoundObj(status);
        setIsPlaying(true);
        setCurrentAudioIndex(index);
      }
    }
  };

  const [isEditing, setIsEditing] = useState(false);
  const confirmEdit = async () => {
    setIsEditing(true);
    let filedata = {
      _id: MyQuesData[myQuesIndex].filedata._id,
      image: imageList,
      soundfile: audioList,
      video: videoList,
    };
    let isSuccess = true;
    await editFileData(
      myQuesIndex,
      filedata,
      originImage,
      deleteOriginImage,
      originAudio,
      deleteOriginAudio,
      originVideo,
      deleteOriginVideo,
      (value) => {
        isSuccess = value;
      }
    );
    setIsEditing(false);
    if (isSuccess) {
      navigation.goBack();
    }
  };

  const handleUpdateFile = async () => {
    await confirmEdit();
  };

  const isOpen = false;

  return (
    <View style={styles.container}>
      {isOpen ? (
        <View>
          <LoadingBar visible={isConfirm} />
          <ScrollView style={{ height: "90%" }}>
            {/* 上传图片 */}
            <View style={styles.section}>
              <View style={styles.tagItem}>
                <Text style={styles.tagtitle}>入户图片</Text>
                {/* 点击+号添加图片 */}
                {imageList.length != 0 || originImage.length != 0 ? (
                  <TouchableOpacity
                    onPress={() => {
                      setIsVisible(true);
                    }}
                    style={styles.smalladdimage}
                  >
                    <MaterialIcons
                      name="add-a-photo"
                      size={20}
                      color="#bcbcbc"
                    />
                  </TouchableOpacity>
                ) : null}
              </View>

              {/* 点击+号添加图片 */}
              {imageList.length == 0 && originImage.length == 0 ? (
                <TouchableOpacity
                  onPress={() => {
                    setIsVisible(true);
                  }}
                  style={[styles.addimage, { marginLeft: 15 }]}
                >
                  <MaterialIcons name="add-a-photo" size={40} color="#bcbcbc" />
                </TouchableOpacity>
              ) : null}

              {/* 图片列表 */}
              <View style={styles.imageList}>
                {/* 原始图片 */}
                {originImage.map((image, index) => {
                  return (
                    <View key={index}>
                      {/* 删除图片按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          deleteOriImage(image);
                        }}
                        style={
                          index % 3 == 2
                            ? styles.lastcoldeleteimage
                            : styles.deleteimage
                        }
                      >
                        <Feather
                          name="x"
                          size={15}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 图片列表，点击放大 */}
                      <TouchableOpacity
                        onPress={() => {
                          let originImageUrl = originImage.map((item) => {
                            return fileWeb + "/" + item.filePath;
                          });
                          let newimageList = [
                            ...originImageUrl,
                            ...imageList,
                          ].map((item) => ({
                            url: item,
                            props: {},
                          }));
                          setimagesUrl(newimageList);
                          setIndex(index);
                          setMagnifypVisible(true);
                        }}
                      >
                        <Image
                          source={{ uri: fileWeb + "/" + image.filePath }}
                          loadingIndicatorSource={require("../../../../assets/interview/loading.png")}
                          style={[
                            index % 3 == 2
                              ? styles.lascolsingleimage
                              : styles.singleimage,
                            { resizeMode: "cover" },
                          ]}
                        />
                      </TouchableOpacity>
                    </View>
                  );
                })}
                {imageList.map((imageurl, index) => {
                  return (
                    <View key={index}>
                      {/* 删除图片按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          deleteImage(imageurl);
                        }}
                        style={
                          (index + originImage.length) % 3 == 2
                            ? styles.lastcoldeleteimage
                            : styles.deleteimage
                        }
                      >
                        <Feather
                          name="x"
                          size={15}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 图片列表，点击放大 */}
                      <TouchableOpacity
                        onPress={() => {
                          let originImageUrl = originImage.map((item) => {
                            return fileWeb + "/" + item.filePath;
                          });
                          let newimageList = [
                            ...originImageUrl,
                            ...imageList,
                          ].map((item) => ({
                            url: item,
                            props: {},
                          }));
                          setimagesUrl(newimageList);
                          setIndex(index + originImage.length);
                          setMagnifypVisible(true);
                        }}
                      >
                        <Image
                          source={{ uri: imageurl }}
                          style={[
                            (index + originImage.length) % 3 == 2
                              ? styles.lascolsingleimage
                              : styles.singleimage,
                            { resizeMode: "cover" },
                          ]}
                        />
                      </TouchableOpacity>
                    </View>
                  );
                })}
              </View>

              {/* 拍照/打开相机Modal */}
              <Modal
                animationType="fade"
                transparent={true}
                visible={isVisible}
              >
                <View style={styles.ModalBackground}></View>

                <TouchableWithoutFeedback
                  onPress={() => {
                    setIsVisible(false);
                  }}
                >
                  <View style={styles.ModalTop}></View>
                </TouchableWithoutFeedback>

                <View style={styles.ModalStyle}>
                  <TouchableOpacity
                    style={styles.ModalOption}
                    onPress={() => {
                      openCamera();
                    }}
                  >
                    <Text style={styles.ModalText}>拍摄</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                    onPress={() => pickImage()}
                  >
                    <Text style={styles.ModalText}>从相册选择</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={styles.ModalOption}
                    onPress={() => {
                      setIsVisible(false);
                    }}
                  >
                    <Text style={styles.ModalText}>取消</Text>
                  </TouchableOpacity>
                </View>
              </Modal>
            </View>

            {/* 放大图片 */}
            <Modal visible={magnifypVisible} animationType={"fade"}>
              <ImageViewer
                imageUrls={imagesUrl}
                menuContext={{ saveToLocal: "保存图片", cancel: "取消" }}
                loadingRender={() => {
                  return <Loading text="Loading"></Loading>;
                }}
                index={index}
                onClick={() => {
                  setMagnifypVisible(false);
                }}
                onSave={() => {
                  saveImage(imagesUrl[index].url);
                }}
              />
            </Modal>

            {/* 上传录音 */}
            <View style={styles.section}>
              <View style={styles.tagItem}>
                <Text style={styles.tagtitle}>入户录音</Text>
                {/* 添加录音按钮 */}
                {audioList.length != 0 || originAudio.length != 0 ? (
                  <TouchableOpacity
                    onPress={() => {
                      pickAudio();
                    }}
                    style={[styles.smalladdimage]}
                  >
                    <Foundation name="record" size={20} color="#bcbcbc" />
                  </TouchableOpacity>
                ) : null}
              </View>
              {/* 添加录音按钮 */}
              {audioList.length == 0 && originAudio.length == 0 ? (
                <TouchableOpacity
                  onPress={() => {
                    pickAudio();
                  }}
                  style={[styles.addimage, { marginLeft: 15 }]}
                >
                  <Foundation name="record" size={45} color="#bcbcbc" />
                </TouchableOpacity>
              ) : null}

              <View style={styles.audiolistStyle}>
                {originAudio.map((item, index) => {
                  return (
                    <AudioListItem
                      key={index}
                      audioName={"录音" + (index + 1)}
                      isPlaying={isPlaying}
                      activeListItem={currentAudioIndex === index}
                      onAudioPress={() => handleAudioPress(item)}
                      deleteAudio={() => deleteOriAudio(item)}
                      downloadAudio={() => {
                        saveAudioAlert(0, item);
                      }}
                    />
                  );
                })}
                {audioList.map((item, index) => {
                  return (
                    <AudioListItem
                      key={index}
                      audioName={item.name}
                      isPlaying={isPlaying}
                      activeListItem={
                        currentAudioIndex === index + originAudio.length
                      }
                      onAudioPress={() => handleAudioPress(item)}
                      deleteAudio={() => deleteAudio(item)}
                      downloadAudio={() => {
                        saveAudioAlert(1, item);
                      }}
                    />
                  );
                })}
              </View>
            </View>

            {/* 上传视频 */}
            <View style={styles.section}>
              <View style={styles.tagItem}>
                <Text style={styles.tagtitle}>入户视频</Text>
                {/* 添加视频按钮 */}
                {videoList.length != 0 || originVideo.length != 0 ? (
                  <TouchableOpacity
                    onPress={() => {
                      setIsVideoVisible(true);
                    }}
                    style={[styles.smalladdimage]}
                  >
                    <MaterialIcons
                      name="video-collection"
                      size={20}
                      color="#bcbcbc"
                    />
                  </TouchableOpacity>
                ) : null}
              </View>

              {/* 添加视频按钮 */}
              {originVideo == 0 && videoList.length == 0 ? (
                <TouchableOpacity
                  onPress={() => {
                    setIsVideoVisible(true);
                  }}
                  style={[styles.addimage, { marginLeft: 15 }]}
                >
                  <MaterialIcons
                    name="video-collection"
                    size={40}
                    color="#bcbcbc"
                  />
                </TouchableOpacity>
              ) : null}

              <View style={styles.videoList}>
                {/* 原始视频 */}
                {originVideo.map((video, index) => {
                  return (
                    <View key={index}>
                      {/* 删除视频的按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          deleteOriVideo(video);
                        }}
                        style={styles.deletevideo}
                      >
                        <Feather
                          name="x"
                          size={19}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 下载视频的按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          saveVideoAlert(fileWeb + "/" + video.filePath);
                        }}
                        style={styles.downloadvideo}
                      >
                        <Feather
                          name="download"
                          size={19}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 视频列表 */}
                      <View style={{ marginBottom: 10 }}>
                        <VideoPlayer
                          videoProps={{
                            shouldPlay: false,
                            resizeMode: ResizeMode.CONTAIN,
                            source: {
                              uri: fileWeb + "/" + video.filePath,
                            },
                          }}
                          style={{
                            height: inFullscreen
                              ? DEVICE_WIDTH
                              : (DEVICE_WIDTH * 3) / 5,
                            width: inFullscreen
                              ? DEVICE_HEIGHT
                              : (DEVICE_WIDTH * 4) / 5,
                            videoBackgroundColor: "#000000",
                          }}
                        />
                      </View>
                    </View>
                  );
                })}
                {/* 新增视频 */}
                {videoList.map((videourl, index) => {
                  return (
                    <View key={index}>
                      {/* 删除视频的按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          deleteVideo(videourl);
                        }}
                        style={styles.deletevideo}
                      >
                        <Feather
                          name="x"
                          size={19}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 下载视频的按钮 */}
                      <TouchableOpacity
                        onPress={() => {
                          saveVideoAlert(videourl);
                        }}
                        style={styles.downloadvideo}
                      >
                        <Feather
                          name="download"
                          size={19}
                          color="#ffffff"
                          style={{ zIndex: 10 }}
                        />
                      </TouchableOpacity>
                      {/* 视频列表 */}
                      <View style={{ marginBottom: 10 }}>
                        <VideoPlayer
                          videoProps={{
                            shouldPlay: false,
                            resizeMode: ResizeMode.CONTAIN,
                            source: {
                              uri: videourl,
                            },
                          }}
                          style={{
                            height: inFullscreen
                              ? DEVICE_WIDTH
                              : (DEVICE_WIDTH * 3) / 5,
                            width: inFullscreen
                              ? DEVICE_HEIGHT
                              : (DEVICE_WIDTH * 4) / 5,
                            videoBackgroundColor: "#000000",
                          }}
                        />
                      </View>
                    </View>
                  );
                })}

                {/* 摄像/打开相册Modal */}
                <Modal
                  animationType="fade"
                  transparent={true}
                  visible={isVideoVisible}
                >
                  <View style={styles.ModalBackground}></View>

                  <TouchableWithoutFeedback
                    onPress={() => {
                      setIsVideoVisible(false);
                    }}
                  >
                    <View style={styles.ModalTop}></View>
                  </TouchableWithoutFeedback>

                  <View style={styles.ModalStyle}>
                    <TouchableOpacity
                      style={styles.ModalOption}
                      onPress={() => {
                        openVideoCamera();
                      }}
                    >
                      <Text style={styles.ModalText}>摄像</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                      style={[styles.ModalOption, { borderBottomWidth: 4 }]}
                      onPress={() => pickVideo()}
                    >
                      <Text style={styles.ModalText}>从相册选择</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                      style={styles.ModalOption}
                      onPress={() => {
                        setIsVideoVisible(false);
                      }}
                    >
                      <Text style={styles.ModalText}>取消</Text>
                    </TouchableOpacity>
                  </View>
                </Modal>
              </View>
            </View>
          </ScrollView>
          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => {
              handleUpdateFile();
            }}
          >
            <Text style={{ color: "#fff" }}>确认</Text>
          </TouchableOpacity>
          <Modal animationType="fade" transparent={true} visible={isEditing}>
            <Loading text="添加中"></Loading>
          </Modal>
        </View>
      ) : (
        <View
          style={{
            height: "100%",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Text>此功能暂不开放</Text>
        </View>
      )}
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
  },
  section: {
    marginLeft: 20,
    marginBottom: 20,
    marginRight: 20,
  },
  tagItem: {
    borderBottomWidth: 1,
    borderBottomColor: "#cccccc",
    paddingBottom: 5,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 15,
  },
  tagtitle: {
    fontSize: 18,
    marginLeft: 10,
    fontWeight: "bold",
  },
  tagborder: {
    width: DEVICE_WIDTH / 4,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 1,
    borderColor: "#d1d1d6",
    borderRadius: 2,
    marginBottom: 10,
  },
  tag: {
    color: "#d1d1d6",
    fontSize: 14,
    includeFontPadding: false,
    textAlignVertical: "center",
    paddingBottom: 4,
    paddingTop: 4,
  },
  //入户图片位置信息
  imageList: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "flex-start",
    alignContent: "center",
    paddingHorizontal: ((DEVICE_WIDTH * 3) / 20 - 40) / 2,
  },
  videoList: {
    flexDirection: "column",
    justifyContent: "flex-start",
    alignItems: "center",
    marginBottom: 20,
  },
  //删除图标的位置信息
  deleteimage: {
    position: "absolute",
    zIndex: 5,
    right: DEVICE_WIDTH / 20,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  //最后一列删除图标的位置信息
  lastcoldeleteimage: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  deletevideo: {
    position: "absolute",
    zIndex: 5,
    right: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  downloadvideo: {
    position: "absolute",
    zIndex: 5,
    left: 0,
    top: 0,
    backgroundColor: "#727272",
    opacity: 0.7,
    padding: 2,
  },
  addimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    backgroundColor: "#efefef",

    marginBottom: DEVICE_WIDTH / 20,
    alignItems: "center",
    justifyContent: "center",
  },
  smalladdimage: {
    width: DEVICE_WIDTH / 11,
    height: DEVICE_WIDTH / 11,
    backgroundColor: "#efefef",

    marginRight: 2,
    marginBottom: 3,
    alignItems: "center",
    justifyContent: "center",
  },
  singleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginRight: DEVICE_WIDTH / 20,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  lascolsingleimage: {
    width: DEVICE_WIDTH / 4,
    height: DEVICE_WIDTH / 4,
    marginBottom: DEVICE_WIDTH / 20,
    position: "relative",
    resizeMode: "contain",
  },
  // 拍照/打开相机背景样式
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalTop: {
    flex: 1,
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalOption: {
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  ModalText: {
    alignSelf: "center",
    fontSize: 16,
    color: "#201D1D",
  },
  audiolistStyle: {
    paddingTop: 10,
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
  },
  submitBtn: {
    height: "10%",
    marginLeft: 20,
    marginRight: 20,
    marginTop: 8,
    marginBottom: 10,
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    flex: 2,
    // width: 200,
  },
  alterView: {
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default AddData;
